package hu.webdream.android.contacts;

import java.util.ArrayList;
import java.util.List;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.provider.BaseColumns;

public class ContactDAO {
	private final SQLiteDatabase db;
	private final ContactDbHelper dbHelper;

	public ContactDAO(Context context) {
		this.dbHelper = new ContactDbHelper(context);
		this.db = this.dbHelper.getWritableDatabase();
	}

	public void close() {
		this.db.close();
	}

	/**
	 * Create new
	 * 
	 * @param name
	 * @param phone
	 */
	public void createContact(String name, String phone) {
		ContentValues contentValues = new ContentValues();
		contentValues.put(ContactDbHelper.NAME, name);
		contentValues.put(ContactDbHelper.PHONE, phone);
		this.db.insert(ContactDbHelper.TABLE_NAME, null, contentValues);
	}

	/**
	 * Delete one
	 * 
	 * @param contactId
	 */
	public void deleteContact(int contactId) {
		this.db.delete(ContactDbHelper.TABLE_NAME, BaseColumns._ID + " = "
				+ contactId, null);
	}

	/**
	 * Get all
	 * 
	 * @return
	 */
	public List<Contact> getAll() {
		List<Contact> contactList = new ArrayList<Contact>();

		// Name of the columns we want to select
		String[] tableColumns = new String[] { BaseColumns._ID,
				ContactDbHelper.NAME, ContactDbHelper.PHONE };

		// Query the database
		Cursor cursor = this.db.query(ContactDbHelper.TABLE_NAME, tableColumns,
				null, null, null, null, null);
		cursor.moveToFirst();

		// Iterate the results
		while (!cursor.isAfterLast()) {
			Contact contact = new Contact();
			// Take values from the DB
			contact.setId(cursor.getInt(0));
			contact.setName(cursor.getString(1));
			contact.setPhone(cursor.getString(2));

			// Add to the list
			contactList.add(contact);

			// Move to the next result
			cursor.moveToNext();
		}

		return contactList;
	}

}
